package cn.my.learning.Interceptor;

import cn.my.learning.domain.WebPageHistory;
import cn.my.learning.repository.PageHistoryRepository;
import cn.my.learning.util.IsLoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Leo on 2017/3/29.
 * Web页面控制配置类
 */
@Configuration
public class WebPageConfig extends WebMvcConfigurerAdapter {

    /**
     * 登录session key
     */
    public final static String SESSION_KEY = "MY_User_SessionKey";

    //拦截器排除配置(待添加)
    private final static  String[] excludePath = {"/libraryList/get_libraryList",
            "/configuration/security", "/get_libraryCollection", "/swagger-resources",
            "/configuration/ui", "/get_one_library","/addArticleComment",
            "/get_my_library", "/getGuestRecommend", "/getUserPersonalRecommend",
            "/get_externalLinkList", "/get_all_external_link", "/get_userInfo",
            "/getRecommend","/get_all_userInfo","/get_articleCollection",
            "/get_all_ExternalLinkLibraryName","/get_userArticle","/get_external_link_byLibraryCode",
            "/getArticleComment","/get_allAccount","/get_research",
            "/get_my_libraryName", "/accountLogin", "/v2/api-docs",
            "/loginStatus", "/addAccount", "/userInfo",
            "/image", "/error", "/404",
            "/500", "/"};

    @Bean
    public WebpageInterceptor getWebpageInterceptor() {
        return new WebpageInterceptor();
    }

    public void addInterceptors(InterceptorRegistry registry) {
        //注册一个拦截器
        InterceptorRegistration addInterceptor = registry.addInterceptor(getWebpageInterceptor());

        // 排除配置(避免写入过多对推荐没有意义的浏览记录)
        addInterceptor.excludePathPatterns(excludePath);

        // 拦截配置
        addInterceptor.addPathPatterns("/**");
    }

    //自定义拦截器，实现HandlerInterceptor
    private class WebpageInterceptor implements HandlerInterceptor {

        @Autowired
        private PageHistoryRepository pageHistoryRepository;

        //logger
        private final Logger logger = LoggerFactory.getLogger(cn.my.learning.Interceptor.WebPageConfig.class);

        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            logger.info(">>>WebpageInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            logger.info(">>>WebpageInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");

            //获取用户名并初始化userFolderName
            IsLoginUtil isLoginUtil = new IsLoginUtil();
            String userFolderName = isLoginUtil.IsLogin(httpServletRequest);

            //WebPageHistory
            WebPageHistory webPageHistory = new WebPageHistory();

            //详细记录信息
            String sessionID = httpServletRequest.getRequestedSessionId();
            if ( sessionID == null){
                sessionID = "";
            }

            //记录sessionID
            webPageHistory.setSessionId(sessionID);

            //获得页面路径传参的参数，主要服务于外链跳转通过form表单提交的目标地址，精细化推荐
            //有参数则在URI后面加上参数，无则直接写入对象
            String parameter = httpServletRequest.getParameter("target");
            if(parameter != null){
                String pageUri = httpServletRequest.getRequestURI() + "?target=" + parameter;
                webPageHistory.setPageUri(pageUri);
            }else {
                webPageHistory.setPageUri(httpServletRequest.getRequestURI());
            }

            //记录IP地址
            webPageHistory.setRemoteAddr(httpServletRequest.getRemoteAddr());

            //记录详细的远程地址并加上访问的URL
            webPageHistory.setRemoteAddrURL(httpServletRequest.getRequestURL().toString());

            //记录浏览器的Agent
            webPageHistory.setUserAgent(httpServletRequest.getHeader("User-Agent"));

            //记录访问时间
            webPageHistory.setVisitTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            //记录用户名，如果有的话
            webPageHistory.setUsername(userFolderName);

            //保存对象
            pageHistoryRepository.save(webPageHistory);
        }

        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            logger.info(">>>WebpageInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
        }
    }
}
